#include "exporter.h"

Exporter::Exporter(QString f, QString e, QList< QPointer<Contig> >* contigs, QObject *parent) :
    QObject(parent)
{
    qDebug() << "creating exporter" << endl;

    fastaFileName.append( f );
    exportFileName.append( e );

    for(int i = 0; i < contigs->size(); i++)
    {
        genesToExport+= contigs->at(i)->getSelectedGenes();
    }
}


Exporter::~Exporter()
{

}

void Exporter::process()
{
    qDebug() << "I am in a exporter thread " << endl;

    //Load genes to export into hashtable for quick lookup
    QHash<QString, int> genesToExportLookup;
    for(int i = 0 ; i < genesToExport.size(); i++)
        genesToExportLookup.insert(genesToExport[i], i);

    //Open FASTA file
    QFile fastaFile( fastaFileName );
    if( !fastaFile.exists() )
    {
        qDebug() << "fasta file not found." << endl;
        return;
    }
    if( ! fastaFile.open(QIODevice::ReadOnly))
    {
        qDebug() << "file " << fastaFileName << " can't be opened." << endl;
        return;
    }
    qDebug() << "file " << fastaFileName << " opened." << endl;

    //Get fasta file size, so can keep track of progress
    QFileInfo fastaInfo( fastaFile );
    qint64 totalBytes = fastaInfo.size();

    //Open export write file
    QFile exportFile( exportFileName ); //for now- should prompt user for name
    if( ! exportFile.open(QIODevice::WriteOnly))
    {
        qDebug() << "export file can't be opened." << endl;
        return;
    }
    qDebug() << "export file opened." << endl;

    QTextStream fastaStream(&fastaFile);
    QTextStream exportStream(&exportFile );

    QString line;
    int byteCount = 0;
    int nextPerc = 10;
    bool writeThisLine = false;
    do {
        line = fastaStream.readLine(); //read each line
        //parse each line

        byteCount += line.size();
        int perc = (int)( (float)byteCount /(float)totalBytes * 100.0);
        if( perc == nextPerc )
        {
            emit( trackProgress(perc) );
            nextPerc+=10;
        }
        if( line.contains(">") ) //if is a gene line
        {
            QStringList list = line.split(" ");
            if( genesToExportLookup.contains(list[0].remove(">").remove(".pep")) )//if gene is selected
            {
                writeThisLine = true;//write it to output file
            }
            else
                writeThisLine = false;
        }

        //will write lines from selected gene though its sequence- will stop at non-selected gene
        if( writeThisLine )
            exportStream << line << endl;

    }while( !fastaStream.atEnd());

    qDebug() << "done exporting " << endl;

    fastaFile.close();
    exportFile.close();
    emit( trackProgress(100) );
    emit finished();
}
